﻿namespace Dyao.Book.Core
{
    public static class NetExtensions
    {
        /// <summary>
        /// Url是否有效
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<bool> IsUrlReachableAsync(string url)
        {
            // 验证URL格式
            if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) ||
                (uriResult.Scheme != Uri.UriSchemeHttp && uriResult.Scheme != Uri.UriSchemeHttps))
            {
                Console.WriteLine("无效的URL格式");
                return false;
            }

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    // 设置超时时间（5秒）
                    client.Timeout = TimeSpan.FromSeconds(5);

                    // 发送HEAD请求（比GET更轻量）
                    HttpResponseMessage response = await client.SendAsync(
                        new HttpRequestMessage(HttpMethod.Head, url));

                    // 检查响应状态码是否为成功（2xx）
                    return response.IsSuccessStatusCode;
                }
                catch (HttpRequestException ex)
                {
                    return false;
                }
                catch (TaskCanceledException)
                {
                    return false;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
    }
}
